package com.zyguo.sdk.websocket;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.msgpack.MessagePack;


public class NetTransferUtils {
	private static Logger log = Logger.getLogger( NetTransferUtils.class );
	private static MessagePack msgPack = new MessagePack();

	public static byte[] intToByteArray(int i) {
		byte[] result = new byte[4];
		result[0] = (byte) ((i >> 24) & 0xFF);
		result[1] = (byte) ((i >> 16) & 0xFF);
		result[2] = (byte) ((i >> 8) & 0xFF);
		result[3] = (byte) (i & 0xFF);

		return result;
	}


	// 组包
	public static byte[] getRequestMsg(RequestMsg msg) {
		RequestHeader header = msg.getHeader();
		Object body = msg.getBody();
		byte[] headbytes = null;
		byte[] bodybytes = null;
		try {
			headbytes = msgPack.write(header);
			byte[] msgbytes = ArrayCopy.concatAll(headbytes);
			
			if( body != null ){
				bodybytes = msgPack.write(body);
				msgbytes = ArrayCopy.concatAll( msgbytes, bodybytes );
			}
			return msgbytes;
		} catch (Exception e) {
			log.error("组包异常, headbyte=" + headbytes + ",bodybyte=" + bodybytes, e);
		}
		return null;
	}

	// 解包
	public static ResponseMsg getResponseMsg(byte[] bytes ) throws IOException {
		if( bytes == null ){
			return null;
		}
		ResponseMsg rbody = new ResponseMsg();
		msgPack.read(bytes, rbody);
		return rbody;
	}
	
}
